package com.npy.reggie.contorller;

import com.npy.reggie.doman.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class fIleUploadController {
    @Value("${reggie.path}")
    private String reggiePath;

    @PostMapping("/upload")
    public R<String> upLo(MultipartFile file){
        String suffix= null;
        try {
            suffix = Objects.requireNonNull(file.getOriginalFilename()).
                    substring(file.getOriginalFilename().lastIndexOf("."));
        } catch (Exception e) {
            log.info("上传文件为空");
            e.printStackTrace();
        }

        log.info("上传文件后缀{}",suffix);

        String fileName = UUID.randomUUID().toString()+suffix;

        File dir = new File(reggiePath);

        if (!dir.exists()){
            boolean mkdirs = dir.mkdirs();
        }

        try {
            file.transferTo(new File(reggiePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name , HttpServletResponse response,
                         HttpServletRequest request) throws IOException {

        FileInputStream fis = null;
        ServletOutputStream outputStream = null;
        try {
             fis = new FileInputStream(reggiePath+name);
             outputStream = response.getOutputStream();

            response.setContentType(request.getServletContext().getMimeType(name));
            /*int len;
            byte[] bytes = new byte[1024];

            while ((len=fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }*/
            IOUtils.copy(fis,outputStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("下载文件不存在");
        }finally {
            if (outputStream!=null){
                outputStream.close();
            }
            if (fis!=null){
                fis.close();
            }
        }


    }

}
